import {
  getStandFileInfoByPage,
  addStandFileInfo,
  uploadStandFileInfoDrawing,
  uploadStandFileInfoBom,
  delStandFileInfo,
  exportStandFileInfo,
  getProductTypeList,
  getStandFileType,
  downloadFile,
  getDrawingTypeList,
  getStandFileInfoByStandTypeIdAndCategoryPage,
  switchStandFileInfo,
  getPreviewUrl,
} from '@/services/design/standFileInfo';
import {
  PlusOutlined,
  UploadOutlined,
  ArrowLeftOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Select,
  Upload,
  Descriptions,
  Tooltip,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import { Ellipsis } from '@/components/Ellipsis';
import { values } from 'lodash';
const StandFileInfodrawing: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [fileList, setFileList] = useState([]);
  const [category, setcategory] = useState();
  const [optionsTypeDesc, setoptionsTypeDesc] = useState([]); //下拉框用到
  const [optionsstandfile, setoptionsstandfile] = useState([]);

  StandFileInfodrawing.defaultProps = {
    thisstandTypeCode: '',
    thisstandTypeDesc: '',
    thisstandid: '',
    thisstandname: '',
    thisstate: '',
  };
  const thisstandTypeCode = props.thestandTypeCode;
  const thisstandTypeDesc = props.thestandTypeDesc;
  const thisstandid = props.thestandid;
  const thisstandname = props.thestandname;
  const thisstate = props.thestate;
  const [form] = Form.useForm();
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '柜体类型',
    //   dataIndex: 'standTypeDesc',
    // },
    // {
    //   title: '柜体编号',
    //   dataIndex: 'standTypeCode',
    // },
    // {
    //   title: '柜体名称',
    //   dataIndex: 'standTypeName',
    // },
    {
      title: '文件类别',
      dataIndex: 'category',
      width: 100,

      align: 'center',
      sorter: true,
    },
    {
      title: '文件编号',
      dataIndex: 'fileCode',
      width: 200,

      align: 'center',
      sorter: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      width: 200,
      ellipsis: true,

      align: 'center',
      sorter: true,
    },
    // {
    //   title: '版本号',
    //   dataIndex: 'version',
    //   render: (text, record, _, action) => {
    //     return <div>{text}</div>;
    //   },
    //   width: 80,
    //   align: 'center',
    //   sorter: true,
    // },
    // {
    //   title: '启用状态',
    //   dataIndex: 'status',
    //   render: (text, record, _, action) => {
    //     return <div>{record.status == 1 ? '是' : '否'}</div>;
    //   },
    //   width: 80,

    //   align: 'center',
    //   sorter: true,
    // },
    // {
    //   title: '文件后缀',
    //   dataIndex: 'fileExtEndDate',
    //   width: 80,
    // },
    // {
    //   title: '文件大小',
    //   dataIndex: 'fileSize',
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    // },
    {
      title: '上传人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 100,
      align: 'center',
      sorter: true,
    },
    {
      title: '上传日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      width: 100,

      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 160,
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={async () => {
            if (
              record.fileExtEndDate == 'pdf' ||
              record.fileExtEndDate == 'png' ||
              record.fileExtEndDate == 'jpg'
            ) {
              const url = await getPreviewUrl(record);
              const w = window.open('about:blank');
              w.location.href = url.message;
            } else {
              downloadFile({ standFileId: record.id }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `${record.fileName}`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }
          }}
        >
          预览下载
        </a>,
        <a
          key="deleteKey"
          hidden={thisstate !== 0}
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delStandFileInfo({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
        // <a
        //   key="useKey"
        //   onClick={async () => {
        //     if (record.status == '1') {
        //       message.warning('当前图纸已启用');
        //     }
        //     if (record.status == '-1') {
        //       const fileinfoparams = {
        //         category: record.category,
        //         standFileInfoId: record.id,
        //         standTypeId: record.standTypeId,
        //         status: '1',
        //       };
        //       console.log(fileinfoparams);
        //       const result = await switchStandFileInfo(fileinfoparams);
        //       if (result != null) {
        //         message.success('启用成功');
        //         actionRef.current.reload();
        //       }
        //     }
        //   }}
        // >
        //   启用
        // </a>,
        // <a
        //   key="nonuseKey"
        //   onClick={async () => {
        //     if (record.status == '-1') {
        //       message.warning('当前图纸已禁用');
        //     }
        //     if (record.status == '1') {
        //       const fileinfoparams = {
        //         category: record.category,
        //         standFileInfoId: record.id,
        //         standTypeId: record.standTypeId,
        //         status: '-1',
        //       };
        //       console.log(fileinfoparams);
        //       const result = await switchStandFileInfo(fileinfoparams);
        //       if (result != null) {
        //         message.success('禁用成功');
        //         actionRef.current.reload();
        //       }
        //     }
        //   }}
        // >
        //   禁用
        // </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '上传图纸附件') {
      form
        .validateFields()
        .then(async () => {
          const res = {
            ...form.getFieldsValue(),
            standTypeCode: thisstandTypeCode,
            standTypeDesc: thisstandTypeDesc,
            standTypeId: thisstandid,
            standTypeName: thisstandname,
          };
          console.log('附件信息：', res.file.fileList);
          const formData = new window.FormData();
          res.file.fileList.map((file: any) => {
            formData.append('file', file.originFileObj);
          });
          res.file = formData;
          const result = await uploadStandFileInfoDrawing(res);
          if (result != null) {
            message.success('添加成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current.reload();
        })
        .catch(() => {
          console.log('提交失败');
          setConfirmLoading(false);
        });
    }
  };

  const getproductInfo = async () => {
    // 获取图纸类型
    const gettype = await getDrawingTypeList(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      if (item == '电气原理图' || item == '箱柜接线表') {
        productfiletype.push({ value: item, label: item + ' *' });
      } else {
        productfiletype.push({ value: item, label: item });
      }
    });
    setoptionsstandfile(productfiletype);
  };

  const onFilesChange = (info: any) => {
    console.log(info);
    setFileList(info.fileList);
  };
  // 限制图纸大小
  const handleBeforeUpload = (info: any) => {
    //检验文件大小
    // info.size文件大小单位是字节
    // const isLt = info.size / 1024 / 1024 < 5;
    // if (!isLt) {
    //   alert(`上传文件大小不能超过 ${5} MB!`);
    // }
    // return isLt || Upload.LIST_IGNORE;
    return false;
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="标准柜体图纸列表"
        scroll={{ x: 1500, y: 300 }}
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          // <Button
          //   key="button"
          //   icon={<ArrowLeftOutlined />}
          //   onClick={() => {
          //     history.push('/design/standProduct');
          //   }}
          //   type="primary"
          // >
          //   返回
          // </Button>,
          // eslint-disable-next-line react/jsx-key
          <div className="standFileInfoTooltipStyle">
            <ExclamationCircleOutlined />
            <span>上传须知：需要上传并启用“电气原理图”和“箱柜接线表”</span>
          </div>,
          <Button
            key="button"
            icon={<UploadOutlined />}
            hidden={thisstate !== 0}
            onClick={() => {
              setCreateOrUpdate(true);
              setFormTitle('上传图纸附件');
              setModalVisit(true);
            }}
            type="primary"
          >
            上传
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const drawingparams = {
            category: '图纸',
            pageEntity: {
              current: 1,
              filters: filters,
              pageSize: 6,
              sorters: sorters,
            },
            standTypeId: thisstandid,
          };
          const result = await getStandFileInfoByStandTypeIdAndCategoryPage(drawingparams);
          //日期处理，只保留日期的年月日部分
          result.data.content.map((item: any) => {
            item.createTime = item.createTime.split(' ')[0];
          });
          // console.log(result.data.content);
          getproductInfo();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择柜体类型!' }]}
          >
             <Select
              placeholder="请选择柜体类型"
              disabled  //不可更改
              onChange={(value, label) => {  }}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
          >
            <Input disabled/>
          </Form.Item> */}
          <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select placeholder="请选择文件类别" onChange={() => {}} options={optionsstandfile} />
          </Form.Item>
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            {/* <div key={Math.random()}> */}
            <Upload
              file-list="file"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
            {/* </div> */}
          </Form.Item>
          {/* <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default StandFileInfodrawing;
